﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace ContentTypeExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection contentTypes = new NameValueCollection();
            ExtractMimeDatabase(contentTypes);
            ExtractClassesRoot(contentTypes);
            var output = new StringBuilder();
            foreach (String key in contentTypes.AllKeys.OrderBy(v=>v))
            {
                var values = contentTypes.GetValues(key);
                if (values != null)
                {
                    foreach (string value in values.OrderBy(v=>v))
                    {
                        output.AppendLine(string.Format("{0}\t{1}", key, value));    
                    }
                }
            }
            Console.WriteLine(output.ToString());
            Console.WriteLine("press enter to exit");
            Console.ReadLine();
        }

        static void ExtractClassesRoot(NameValueCollection contentTypes)
        {
            using (RegistryKey key = Registry.ClassesRoot)
            {
                foreach (string extension in key.GetSubKeyNames())
                {

                    if(extension.StartsWith("."))
                    {
                        using (RegistryKey subKey = key.OpenSubKey(extension))
                        {
                            if (subKey != null)
                            {
                                string contentType = (string)subKey.GetValue("Content Type");
                                if (!string.IsNullOrEmpty(contentType))
                                {
                                    contentTypes.Add(extension, contentType);    
                                }
                            }
                        }
                    }
                }
            }
        }
        static void ExtractMimeDatabase(NameValueCollection contentTypes)
        {
            using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type"))
            {
                if (key != null)
                {
                    foreach (string contentType in key.GetSubKeyNames())
                    {
                        using (RegistryKey subKey = key.OpenSubKey(contentType))
                        {
                            if (subKey != null)
                            {
                                string extension = (string)subKey.GetValue("Extension");
                                contentTypes.Add(extension,contentType);
                            }
                        }
                    }
                }
            }
        }
    }
}
